import React, { useRef, useState } from 'react';
import { Modal, Button, message } from 'antd'
import {
  fileUpload
} from '@/services/register';

import styles from './index.module.less'

const CameraModal = ({
  title = '身份识别',
  btnName = '证件拍照',
  onChangeImage
}) => {
  const videoRef = useRef();
  const canvasRef = useRef();

  const [isOpen, setIsOpen] = useState<boolean>(false);

  const [imgSrc, setImgSrc] = useState(null)


  async function openVideo() {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');

    // const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
    // console.log('mediaStream :>> ', mediaStream);
    navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
      console.log('stream :>> ', stream);
      video.srcObject = stream;
    })
      .catch((error) => {
        console.error('Error accessing camera:', error);
      });
    // Capture photo
    // video.addEventListener('loadedmetadata', () => {
    //   canvas.width = video.videoWidth;
    //   canvas.height = video.videoHeight;
    //   context.drawImage(video, 0, 0, canvas.width, canvas.height);
    //   // Save the photo or perform any other desired operations with the captured image
    //   const photoData = canvas.toDataURL('image/png');
    // });
  }


  //将base64转换为blob
  function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  //将blob转换为file
  function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
  }

  const handleCapture = async () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');

    // // Access the camera
    // navigator.mediaDevices.getUserMedia({ video: true })
    //   .then((stream) => {
    //     video.srcObject = stream;
    //   })
    //   .catch((error) => {
    //     console.error('Error accessing camera:', error);
    //   });
    const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
    // video.srcObject = mediaStream;
    // Capture photo
    // video.addEventListener('loadedmetadata', () => {
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    // Save the photo or perform any other desired operations with the captured image
    const photoData = canvas.toDataURL('image/png');
    setImgSrc(photoData)
    //调用
    let blob = dataURLtoBlob(photoData);
    let file = blobToFile(blob, '');
    // console.log('file :>> ', file, base64Data);
    const formData = new FormData();
    formData.append("file", file);
    const res = await fileUpload(formData);
    if (res?.resultCode === "00000000") {
      message.success(res?.message)
      onChangeImage && onChangeImage(`${UpUrl}${res?.data}`)
      colseModal()
    } else {
      message.error(res?.message)
    }

    // console.log('res :>> ', res.data);
    // });
    // setIsFrist(false)

  };


  async function onColse() {
    const video = videoRef.current;
    const videoTrack = video?.srcObject?.getVideoTracks()[0];
    // /* const mediaStream = await */ navigator.mediaDevices.getUserMedia({ video: false });
    await videoTrack?.stop();
    video?.srcObject?.getTracks().forEach(track => track.stop());
    videoRef.current.srcObject = null;
    console.log('videoTrack :>> ', videoTrack);
  }


  function showModal() {
    openVideo()
    setIsOpen(true);
  }

  async function colseModal() {
    await onColse()
    setImgSrc(null)
    setTimeout(() => {
      setIsOpen(false);
    }, 500)
  }


  return (
    <div className={styles.wrapper}>
      <Modal
        width={800}
        title={title}
        open={isOpen}
        onCancel={colseModal}
        footer={null}
        forceRender
      >
        <>
          <div className={styles.wrap}>
            <div className={styles.videoBox}>
              <div className={styles.name}>取景区</div>
              <video
                className={styles.video}
                ref={videoRef} autoPlay
              // controls
              /* style={{ display: 'none' }} */
              />
            </div>

            <div className={styles.canvasBox}>
              <canvas ref={canvasRef} />
            </div>
            <div className={styles.captureBox}>
              <div className={styles.imgBox}>
                <div className={styles.name}>成像区</div>
                <div className={styles.captureImg}>
                  {imgSrc && <img src={imgSrc} alt='' />}
                </div>
              </div>
              <div className={styles.captureBtn} onClick={handleCapture}>拍照</div>

            </div>

          </div>
          {/* <Button onClick={openVideo}>打开摄像头</Button>
          <Button onClick={onColse}>关闭摄像头</Button> */}
        </>
      </Modal>

      <Button onClick={showModal} type="primary">
        {btnName}
      </Button>
    </div>
  );
};

export default CameraModal;